package com.kb.erp.util;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.kb.erp.service.impl.DYYServiceImpl;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * @Auther:chenzx
 * @Date:2023/9/27
 * @Description:guava缓存
 */
public class GuavaCacheUtil {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(GuavaCacheUtil.class);
    public static LoadingCache<String, String> strCache = CacheBuilder
            .newBuilder()
            .maximumSize(1000)
            //设置过期时间
            .expireAfterAccess(1, TimeUnit.HOURS)
            .build(
                    new CacheLoader<String, String>() {
                        @Override
                        public String load(String s) throws Exception { //当缓存中不存在时，自动加载新数据到缓存
                            return null;
                        }
                    }
            );

    /**
     * 将值存入缓存
     *
     * @param key
     * @param val
     */
    public static void setStr(String key, String val) {
        strCache.put(key, val);
    }

    /**
     * 从缓存中取值
     *
     * @param key
     * @return
     */
    public static String getStr(String key) {
        String val = "";
        try {
            val = strCache.get(key);
        } catch (Exception  e) {
            log.info("缓存获取失败, 已过期");
        }
        return val;
    }
    /**
     * 从缓存中取值
     *
     * @param key
     * @return
     */
    public static void delStr(String key) {
        try {
           strCache.invalidate(key);
        } catch (Exception e) {
            log.info("缓存删除失败"+e.getMessage());
        }
    }

}
